// pages/home/home.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: 'http://127.0.0.1:1189',  // 改为你的后端服务IP和端口
    previewImage: '',
    activeFunction: 'text',
    currentStyle: 'cartoon',
    styleType: 'cartoon',
    textPrompt: '',
    rotationAngle: 0,
    autoSuggestedStyle: '分析中...',
    styleNames: {
      'cartoon': '漫画风',
      'oil_painting': '油画',
      'sketch': '素描',
      'ink_painting': '水墨',
    },
    originalImage: '',
    resultImage: '',
    isProcessing: false,
    globalProcessing: false, // 全局处理状态
    windowInfo: null,
    imageSize: '',
    numInferenceSteps: 20,
    guidanceScale: 7.5,
    negativePrompt: '',
    taskId: '',
    taskStatus: '',
    taskProgress: 0,
    modelUrls: null,
    artStyle: 'realistic',
    pollingTimer: null,
    type: '',
    prompt: '',
    thumbnailUrl: '',
    progress: 0,
    status: 'PENDING',
    pageTitle: '',
    modelViewerUrl: '', // 用于 web-view 显示模型
    modelUrl: '',
    functionNames: {
      'text3d': '文本生成3D模型',
      'photo3d': '照片转3D模型'
    },
    styleSize: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 初始化时格式化引导强度
    this.setData({
      guidanceScale: parseFloat(this.data.guidanceScale).toFixed(1)
    });
    
  },

  /**
   * 检查登录状态并阻止未登录用户操作
   */
  checkLoginBeforeAction() {
    const app = getApp();
    const isLoggedIn = app.isLoggedIn();

    if (!isLoggedIn) {
      app.showUnifiedLoginPrompt();
      return false;
    }
    return true;
  },

  /**
   * 功能切换的公共处理函数
   * @param {string} activeFunction 要切换到的功能标识
   * @param {object} extraData 额外需要设置的数据
   */
  switchToFunction(activeFunction, extraData = {}) {
    // 公共重置数据
    const commonData = {
      originalImage: '',
      resultImage: '',
      imageSize: '',
      numInferenceSteps: 20,
      guidanceScale: 7.5,
      negativePrompt: '',
      styleType: 'cartoon',
      currentStyle: 'cartoon',
      styleSize: '',
      textPrompt: '',
      artStyle: 'realistic',
      taskId: '',
      taskStatus: '',
      taskProgress: 0,
      modelUrls: null,
      modelViewerUrl: '',
      modelUrl: '',
      thumbnailUrl: '',
      progress: 0,
      status: 'PENDING',
      pageTitle: '',
      type: '',
      prompt: '',
      rotationAngle: 0,
      autoSuggestedStyle: '分析中...',
      previewImage: ''
    };

    // 合并公共数据、功能标识和额外数据
    this.setData({
      ...commonData,
      activeFunction,
      ...extraData
    });
  },

  /**
   * 切换到照片风格转换功能
   */
  choosePhotoStyle() {
    this.switchToFunction('style');
  },

  // 选择照片
  choosePhoto() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        this.setData({
          originalImage: tempFilePath
        });

        wx.showToast({
          title: '照片已选择',
          icon: 'success',
          duration: 1500
        });
      }
    });
  },

  /**
   * 切换到文本生成照片功能
   */
  chooseTextToImage(e) {
    this.switchToFunction('text');
  },

  /**
   * 切换到文本生成3D模型功能
   */
  chooseTextTo3D() {
    this.switchToFunction('text3d');
  },

  /**
   * 切换到照片转3D模型功能
   */
  choosePhotoTo3D() {
    this.switchToFunction('photo3d');
  },

  /**
   * 选择风格类型
   */
  selectStyleType(e) {
    const style = e.currentTarget.dataset.style;
    this.setData({
      styleType: style,
      currentStyle: style  // 同步更新currentStyle
    });
  },

  /**
   * 选择风格尺寸
   */
  selectStyleSize(e) {
    const size = e.currentTarget.dataset.size;

    this.setData({
      styleSize: size
    });

    wx.showToast({
      title: `已选择${size === 'small' ? '小' : size === 'medium' ? '中' : '大'}尺寸`,
      icon: 'none',
      duration: 1000
    });
  },

  /**
   * 选择风格
   */
  selectStyle(e) {
    const style = e.currentTarget.dataset.style;
    this.setData({
      currentStyle: style,
      styleType: style
    });
  },

  /**
   * 文本输入处理
   */
  onTextInput(e) {
    this.setData({
      textPrompt: e.detail.value
    });
  },

  /**
   * 封装参数验证函数
   */
  validateParams() {
    const { activeFunction, originalImage, textPrompt, imageSize } = this.data;
    
    if (activeFunction === 'style' && !originalImage) return { valid: false, msg: '请先选择照片' };
    if ((activeFunction === 'text' || activeFunction === 'text3d') && !textPrompt.trim()) 
      return { valid: false, msg: '请输入描述文本' };
    if ((activeFunction === 'style' || activeFunction === 'text') && !imageSize) 
      return { valid: false, msg: '请选择图片尺寸' };
    if (activeFunction === 'photo3d' && !originalImage) return { valid: false, msg: '请先选择照片' };
    
    return { valid: true };
  },

  /**
   * 处理图片
   */
  processImage() {
    // 只在点击生成按钮时检查登录状态
    if (!this.checkLoginBeforeAction()) return;

    if (this.data.isProcessing) {
      wx.showToast({
        title: '正在处理中，请勿重复操作',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    // 检查必要参数
    const validation = this.validateParams();
    if (!validation.valid) {
      wx.showToast({ title: validation.msg, icon: 'none', duration: 2000 });
      return;
    }

    // 原有的处理逻辑
    if (this.data.activeFunction === 'style') {
      this.callStyleTransformAPI();
    } else if (this.data.activeFunction === 'text') {
      this.callTextToImageAPI();
    } else if (this.data.activeFunction === 'text3d') {
      this.callTextTo3DAPI();
    } else if (this.data.activeFunction === 'photo3d') {
      this.callPhotoTo3DAPI();
    }
  },

  /**
   * 调用风格转换API
   */
  callStyleTransformAPI() {
    const { originalImage, styleType, imageSize, numInferenceSteps, guidanceScale, negativePrompt } = this.data;

    // 设置处理状态
    this.setData({ isProcessing: true });

    // 显示全局加载遮罩层
    const app = getApp();
    app.showGlobalLoading();

    // 禁用页面滑动
    wx.setPageStyle({
      style: {
        overflow: 'hidden',
        touchAction: 'none'
      }
    });

    // 将风格类型映射到API需要的格式
    const styleMap = {
      'cartoon': '卡通风格',
      'oil': '油画风格',
      'sketch': '素描风格',
      'ink': '水墨风格'
    };

    wx.uploadFile({
      url: `${this.data.baseUrl}/convert-style`,
      filePath: originalImage,
      name: 'image',
      formData: {
        style: styleMap[styleType] || '卡通风格',
        image_size: imageSize,
        num_inference_steps: parseInt(numInferenceSteps),
        guidance_scale: parseFloat(guidanceScale),
        negative_prompt: negativePrompt || ''
      },

      success: (res) => {
        try {
          const data = JSON.parse(res.data);
          if (data.images && data.images[0] && data.images[0].url) {
            const imageUrl = data.images[0].url;

            // 设置结果图片为网络URL，不立即上传到云存储
            this.setData({
              resultImage: imageUrl
            }, () => {
              // 跳转到结果页面，传递网络URL
              this.navigateToResult('style', imageUrl);
            });
          } else {
            wx.showToast({
              title: '处理失败',
              icon: 'error'
            });
          }
        } catch (err) {
          console.error('解析响应失败：', err);
          wx.showToast({
            title: '服务器响应错误',
            icon: 'error'
          });
        }
      },
      fail: (err) => {
        this.handleAPIError(err, '风格转换失败');
      },
      complete: () => {
        this.setData({ isProcessing: false });

        // 隐藏全局加载遮罩层
        app.hideGlobalLoading();

        // 恢复页面滑动
        wx.setPageStyle({
          style: {
            overflow: 'auto',
            touchAction: 'auto'
          }
        });
      }
    });
  },

  /**
   * 调用文本生成图片API
   */
  callTextToImageAPI() {
    const { textPrompt, imageSize, numInferenceSteps, guidanceScale, negativePrompt } = this.data;

    // 设置处理状态
    this.setData({ isProcessing: true });

    // 显示全局加载遮罩层
    const app = getApp();
    app.showGlobalLoading();

    // 禁用页面滑动
    wx.setPageStyle({
      style: {
        overflow: 'hidden',
        touchAction: 'none'
      }
    });

    wx.request({
      url: `${this.data.baseUrl}/generate-image`,
      method: 'POST',
      data: {
        prompt: textPrompt,
        image_size: imageSize,
        num_inference_steps: parseInt(numInferenceSteps),
        guidance_scale: parseFloat(guidanceScale),
        negative_prompt: negativePrompt || '',
        seed: 4999999999
      },
      success: (res) => {
        if (res.data.images && res.data.images[0] && res.data.images[0].url) {
          const imageUrl = res.data.images[0].url;

          // 设置结果图片为网络URL，不立即上传到云存储
          this.setData({
            resultImage: imageUrl
          }, () => {
            // 跳转到结果页面，传递网络URL
            this.navigateToResult('text', imageUrl);
          });
        } else {
          wx.showToast({
            title: '生成失败',
            icon: 'error'
          });
        }
      },
      fail: (err) => {
        this.handleAPIError(err, '图片生成失败');
      },
      complete: () => {
        this.setData({ isProcessing: false });

        // 隐藏全局加载遮罩层
        app.hideGlobalLoading();

        // 恢复页面滑动
        wx.setPageStyle({
          style: {
            overflow: 'auto',
            touchAction: 'auto'
          }
        });
      }
    });
  },

  /**
   * 调用文本生成3D模型API
   */
  callTextTo3DAPI() {
    const { textPrompt, artStyle } = this.data;

    // 设置处理状态
    this.setData({ isProcessing: true });

    // 显示全局加载遮罩层
    const app = getApp();
    app.showGlobalLoading();

    // 禁用页面滑动
    wx.setPageStyle({
      style: {
        overflow: 'hidden',
        touchAction: 'none'
      }
    });

    wx.request({
      url: `${this.data.baseUrl}/text-to-3d`,
      method: 'POST',

      data: {
        prompt: textPrompt,
        art_style: artStyle
      },
      success: (res) => {
        if (res.data.result) {
          const taskId = res.data.result;
          // 成功获取任务ID后，立即跳转到结果页
          wx.navigateTo({
            url: `/pages/result3d/result3d?type=text3d&task_id=${taskId}&prompt=${encodeURIComponent(textPrompt)}&art_style=${encodeURIComponent(artStyle)}`,
          });
          this.clear3DModelData();
        } else {
          wx.showToast({
            title: '创建任务失败',
            icon: 'error'
          });
        }
      },
      fail: (err) => {
        this.handleAPIError(err, '3D模型生成失败');
      },
      complete: () => {
        this.setData({ isProcessing: false });

        // 隐藏全局加载遮罩层
        app.hideGlobalLoading();

        // 恢复页面滑动
        wx.setPageStyle({
          style: {
            overflow: 'auto',
            touchAction: 'auto'
          }
        });
      }
    });
  },

  /**
   * 调用照片转3D模型API
   */
  callPhotoTo3DAPI() {
    const { originalImage } = this.data;

    // 设置处理状态
    this.setData({ isProcessing: true });

    // 显示全局加载遮罩层
    const app = getApp();
    app.showGlobalLoading();

    // 禁用页面滑动
    wx.setPageStyle({
      style: {
        overflow: 'hidden',
        touchAction: 'none'
      }
    });

    wx.uploadFile({
      url: `${this.data.baseUrl}/image-to-3d/upload`,
      filePath: originalImage,
      name: 'file',
      success: (res) => {
        const data = JSON.parse(res.data);
        if (data.result) {
          const taskId = data.result;
          // 成功获取任务ID后，立即跳转到结果页
          wx.navigateTo({
            url: `/pages/result3d/result3d?type=photo3d&task_id=${taskId}`,
          });
          this.clear3DModelData();
        } else {
          wx.showToast({
            title: '创建任务失败',
            icon: 'error'
          });
        }
      },
      fail: (err) => {
        this.handleAPIError(err, '照片转3D模型失败');
      },
      complete: () => {
        this.setData({ isProcessing: false });

        // 隐藏全局加载遮罩层
        app.hideGlobalLoading();

        // 恢复页面滑动
        wx.setPageStyle({
          style: {
            overflow: 'auto',
            touchAction: 'auto'
          }
        });
      }
    });
  },

  /**
 * 清除3D模型相关数据
 */
  clear3DModelData() {
    this.setData({
      textPrompt: '',
      originalImage: '',
      imageSize: '',
      numInferenceSteps: 20,
      guidanceScale: 7.5,
      negativePrompt: '',
      artStyle: 'realistic'
    });
  },

  /**
   * 切换艺术风格
   */
  toggleArtStyle() {
    this.setData({
      artStyle: this.data.artStyle === 'realistic' ? 'sculpture' : 'realistic'
    });
  },

  /**
   * 统一处理API错误
   */
  handleAPIError(err, defaultMsg = '操作失败，请稍后重试') {
    console.error('API调用失败：', err);
    this.setData({ isProcessing: false });
    
    const app = getApp();
    app.hideGlobalLoading();
    wx.setPageStyle({ style: { overflow: 'auto', touchAction: 'auto' } });
    
    let msg = defaultMsg;
    if (err.statusCode === 401) msg = '认证失败，请重新登录';
    else if (err.statusCode === 429) msg = '请求过于频繁，请稍后再试';
    else if (err.statusCode === 503) msg = '服务暂时不可用，请稍后再试';
    
    wx.showToast({ title: msg, icon: 'error' });
  },

  /**
   * 导航到结果页面
   */
  navigateToResult(type, imageData) {
    try {
      // 显示加载提示
      wx.showLoading({
        title: '加载中...',
        mask: true
      });

      const { originalImage, textPrompt, imageSize, numInferenceSteps, guidanceScale, negativePrompt, taskId } = this.data;

      // 构建参数对象
      const params = {
        type,
        imageData: encodeURIComponent(imageData),
        originalImage: originalImage ? encodeURIComponent(originalImage) : '',
        image_size: encodeURIComponent(imageSize || ''),
        num_inference_steps: encodeURIComponent(numInferenceSteps || ''),
        guidance_scale: encodeURIComponent(guidanceScale || ''),
        negative_prompt: encodeURIComponent(negativePrompt || '')
      };

      if (type === 'style') {
        params.style = this.data.currentStyle;
      } else if (type === 'text3d' || type === 'photo3d') {
        params.prompt = encodeURIComponent(textPrompt || '');
        params.art_style = this.data.artStyle;
        params.task_id = taskId;
      } else {
        params.prompt = encodeURIComponent(textPrompt);
      }

      // 构建查询字符串
      const queryString = Object.entries(params)
        .map(([key, value]) => `${key}=${value}`)
        .join('&');

      // 根据类型选择不同的结果页面
      const targetPage = (type === 'text3d' || type === 'photo3d') ? 'result3d' : 'result';

      // 导航到对应的结果页面
      wx.navigateTo({
        url: `/pages/${targetPage}/${targetPage}?${queryString}`,
        success: () => {
          wx.hideLoading();
          // 跳转成功后清空所有输入数据
          this.setData({
            originalImage: '',
            resultImage: '',
            textPrompt: '',
            imageSize: '',
            numInferenceSteps: 20,
            guidanceScale: 7.5,
            negativePrompt: '',
            isProcessing: false,
            taskId: '',
            taskStatus: '',
            taskProgress: 0,
            modelUrls: null,
            artStyle: 'realistic',
            modelViewerUrl: '',
            modelUrl: '',
            thumbnailUrl: '',
            progress: 0,
            status: 'PENDING',
            pageTitle: '',
            type: '',
            prompt: '',
            currentStyle: 'cartoon',
            styleType: 'cartoon',
            styleSize: '',
            rotationAngle: 0,
            autoSuggestedStyle: '分析中...',
            previewImage: ''
          });
        },
        fail: (error) => {
          console.error('导航失败:', error);
          wx.hideLoading();
          wx.showModal({
            title: '跳转失败',
            content: '请稍后重试',
            showCancel: false
          });
        }
      });

    } catch (error) {
      console.error('导航处理失败:', error);
      wx.hideLoading();
      wx.showModal({
        title: '处理失败',
        content: '请稍后重试',
        showCancel: false
      });
    }
  },

  /**
   * 前往历史记录
   */
  goToHistory() {
    wx.navigateTo({
      url: '/pages/index/index'
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 更新登录状态
    const app = getApp();
    app.updatePageLoginStatus();

    // 确保恢复tabBar显示
    app.hideGlobalLoading();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 清除轮询定时器
    if (this.data.pollingTimer) {
      clearInterval(this.data.pollingTimer);
      this.setData({
        pollingTimer: null,
        taskStatus: '',
        taskProgress: 0,
        taskId: ''
      });
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  onShareTimeline() {
    return {
      title: `生成的3D模型：${this.data.prompt || '照片转3D模型'}`,
      query: '',
      imageUrl: this.data.thumbnailUrl
    };
  },

  /**
   * 返回首页
   */
  goBack() {
    const pages = getCurrentPages();
    if (pages.length > 1) {
      wx.navigateBack();
    } else {
      wx.switchTab({ url: '/pages/home/home' });
    }
  },

  /**
   * 选择图片尺寸
   */
  selectImageSize(e) {
    const size = e.currentTarget.dataset.size;
    this.setData({
      imageSize: size
    });

    wx.showToast({
      title: `已选择尺寸: ${size}`,
      icon: 'none',
      duration: 1000
    });
  },

  /**
   * 推理步数变化处理
   */
  onInferenceStepsChange(e) {
    this.setData({
      numInferenceSteps: e.detail.value
    });
  },

  /**
   * 引导强度变化处理
   */
  onGuidanceScaleChange(e) {
    const formattedValue = parseFloat(e.detail.value).toFixed(1);
    this.setData({
      guidanceScale: formattedValue
    });
  },

  /**
   * 负面提示词输入处理
   */
  onNegativePromptInput(e) {
    this.setData({
      negativePrompt: e.detail.value
    });
  },

  /**
   * 登录状态变化回调
   */
  onLoginStatusChanged() {
    // 更新登录状态
    const app = getApp();
    app.updatePageLoginStatus();
  },

  /**
   * 全局加载状态变化回调
   */
  onGlobalLoadingChanged() {
    const app = getApp();
    this.setData({
      globalProcessing: app.globalData.isGlobalProcessing
    });
  },
})